package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.LoginUser;
import com.crm.pojo.domain.User;
import com.crm.pojo.dto.LoginDto;
import com.crm.pojo.vo.LoginVo;
import com.crm.pojo.vo.RoleVo;
import com.crm.pojo.vo.UserVo;
import com.crm.service.LoginService;
import com.crm.service.RoleService;
import com.crm.service.UserService;
import com.crm.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Override
    public LoginVo login(LoginDto loginDto){
        User user = new User();
        user = userService.getLoginUser(loginDto);
        if (user == null) {
            LoginVo loginVo = new LoginVo();
            loginVo.setCode(500);
            loginVo.setMsg("用户名或密码错误");
            loginVo.setToken("");
            return loginVo;
        }
        // 将用户信息loginUser设置到 UserContext 中
        List<RoleVo> roles = roleService.roles(user.getUserId());
        user.setRoles(roles);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user,loginUser);
        UserContext.setUser(loginUser);
        log.info("用户信息：{}",UserContext.getCurrentUser().getRoles());

        LoginVo loginVo = new LoginVo();
        loginVo.setMsg("操作成功");
        loginVo.setCode(200);
        String token = JwtUtil.generateToken(user.getUserName());
        loginVo.setToken(token);
        return  loginVo;
    }
}
